import { defineComponent, reactive, PropType, watch } from 'vue'
import { DiffOutlined, UndoOutlined, SnippetsOutlined } from '@ant-design/icons-vue'
import { ITableColums } from '@/typings'
import { useParent } from '@/hooks/useExpose'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import { ITableExpose } from '..'
import './tools.less'

interface IState {
  filterCheckAll: boolean;
  filterIndeterminate: boolean;
  filterCheckedList: Array<string | undefined>;
  filterColumns: Array<{ label: string; value: string | undefined }>;
}

export default defineComponent({
  name: 'Tools',
  props: {
    columns: {
      type: Array as PropType<Array<ITableColums>>,
      default: () => []
    },
    exportName: String as PropType<string>,
    onFilter: Function
  },
  emits: ['filter'],
  setup(props, { emit }) {
    const parent: ITableExpose = useParent()
    const filterColumns = props.columns.map((item) => ({ label: item.title, value: item.dataIndex || item.slots?.customRender }))
    const filterCheckedList = filterColumns.map((item) => item.value)

    const state: IState = reactive({
      // tools
      filterCheckAll: true,
      filterIndeterminate: false,
      filterCheckedList,
      filterColumns
    })

    // 改变过滤全选复选框
    const handleChangeGroupAll = (e: { target: { checked: boolean } }) => {
      (state.filterCheckedList as Array<string | undefined>) = e.target.checked ? filterCheckedList : []
      state.filterIndeterminate = false
    }

    // 改变过滤复选框
    const handleChangeFilterCheckGroup = (): void => {
      state.filterCheckAll = state.filterCheckedList.length === state.filterColumns.length
      state.filterIndeterminate = !!state.filterCheckedList.length && state.filterCheckedList.length < state.filterColumns.length
    }

    // 通过监听勾选 过滤表单数据
    watch(() => state.filterCheckedList, (val) => {
      emit('filter', val)
    })

    // 导出
    const exportExcel = () => {
      const tableNode = XLSX.utils.table_to_book(parent.table.value.$el)
      const wbout = XLSX.write(tableNode, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${props.exportName}.xlsx`)
      } catch (e) { console.error(e) }
    }

    const resetTableData = () => {
      parent.handleGetData(1, 10)
    }

    // 过滤
    const filterSlots = () => {
      const slots = {
        content: () => (
          <>
            <a-checkbox
              v-model={[state.filterCheckAll, 'checked']}
              indeterminate={state.filterIndeterminate}
              onChange={handleChangeGroupAll}
            >
              全选
            </a-checkbox>
            <a-checkbox-group
              class="filter-group"
              v-model={[state.filterCheckedList, 'value']}
              options={state.filterColumns}
              onChange={handleChangeFilterCheckGroup}
            />
          </>
        )
      }

      return {
        default: () => (
          <a-popover class="filter-popover" placement="bottom" trigger="click" v-slots={slots}>
            <a-button type="primary" style={{ padding: 0, width: '32px' }}><DiffOutlined /></a-button>
          </a-popover>
        ),
        title: () => <span>过滤</span>
      }
    }

    // 刷新
    const refreshSlots = () => {
      const slots = {
        icon: () => <UndoOutlined />
      }

      return {
        default: () => (
          <a-button onClick={resetTableData} type="primary" v-slots={slots} />
        ),
        title: () => (<span>刷新</span>)
      }
    }

    const exportSlots = () => {
      const slots = {
        icon: () => <SnippetsOutlined />
      }

      return {
        default: () => (
          <a-button onClick={exportExcel} type="primary" v-slots={slots} />
        ),
        title: () => (<span>导出</span>)
      }
    }

    return () => {
      return (
        <div class="tools-bar">
          <a-button-group>
            <a-tooltip placement="topLeft" v-slots={filterSlots()} />
            <a-tooltip placement="topLeft" v-slots={refreshSlots()} />
            <a-tooltip placement="topLeft" v-slots={exportSlots()} />
          </a-button-group>
        </div>
      )
    }
  }
})
